package com.database;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper {
    public static Connection getConnection() {
        Connection connection = null;
        String url = "jdbc:mysql://127.0.0.1:3306/myblog";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, "root", "chenhui");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
        List<String> tableNames = new ArrayList<>();
        while (tables.next()) {
            tableNames.add(tables.getString(3));
        }
        showTables(conn, tableNames);
        conn.close();
    }

    public static void showTables(Connection conn, List<String> tables) throws Exception{
        Statement statement = conn.createStatement();
        for (String tableName : tables) {
            ResultSet resultSet = statement.executeQuery("select * from " + tableName);
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnname = metaData.getColumnLabel(i);
                int columnWidth = metaData.getColumnDisplaySize(i);
                System.out.println(columnname + ", " + columnWidth);
            }
        }
    }
}

